$(document).ready(function() { 
	
	jQuery.getScript(path()+'js/BelleNuitParser.js');
	jQuery.getScript(path()+'js/jquery.caret.1.02.min.js');
	
	$('.step1 .loadDefaults').click(function(e) {
		e.preventDefault();
		app.loadDefaults();
		return false;
	});

	$('.step2').hide();
	$('.step1-proceed').click(function(e) {
		e.preventDefault();
		app.run();
		return false;
	});
	$('.toggle-linenums').click(function(e) {
		e.preventDefault(); 
		$('.toggle-linenums').toggleClass('active');
		toggleLineNumbers();
		return false;
	});
	
	

	$('textarea.file-a').scroll(function() {
		$('textarea.file-b').scrollTop( $('textarea.file-a').scrollTop() );
	})
	
	$('textarea.file-b').scroll(function() {
		$('textarea.file-a').scrollTop( $('textarea.file-b').scrollTop() );
	})

	
	
	setTimeout(onresize, 100);
	$(window).resize(onresize); 
});
 
var onresize = function() { 
	$('table').each(function(i,table) {
		table = $(table);
		var table_height = $(window).height() - table.position().top - 5;			 
		table.height( table_height );			
		table.find('.panel').height(  table_height - 10  )
		 
		table.find('textarea').height(  table_height - 90  ) 
	}); 
}
var toggleLineNumbers = function() {
	 
	$('textarea').each(function(a,textarea) {
		$(textarea).toggleClass('line-numbers');
		var result = [];
		var line_num = 0;
		var lines = $(textarea).val().split('\n');
		$(lines).each(function(i,line) {
			if ($(textarea).hasClass('line-numbers')) {
				if (line.substr(0,3) == '/tc') {
					line = '['+(1+line_num++)+'] ' + line;
				}				
			}
			else {
				if (line.indexOf('/tc') != -1) {
					line = '/tc'+line.split('/tc')[1];
				}
			}
			result.push(line);
		});
		$(textarea).val( result.join('\n') );
	})
};

app = { 
	addChanges: function() {
   
		// split up some lines into two for testing
		var contents = $('textarea.file-b').val();
		var changes = [
	       	{
	       		original: '/tc 10:08:52:16 10:08:55:09\nWe don’t hear about the good things that are happening.',
	       		changed: '/tc 10:08:52:16 10:08:53:09\nWe don’t hear about\n/tc 10:08:53:16 10:08:55:09\nthe good things that are happening.'
			}
		];
		$(changes).each(function(i,obj) {
			contents = contents.replace(obj.original, obj.changed);
		})
		$('textarea.file-b').val(contents)
	},
	
	loadDefaults: function() { 
		$('textarea.file-a').load(path()+'sample-files/bellenuit.txt');
		$('textarea.file-b').load(path()+'sample-files/bellenuit.txt', app.addChanges);
		return '...loading default files.'
	},
	run: function() {
		 
		var a_string = $('textarea.file-a').val();
		var b_string = $('textarea.file-b').val();
		
		if (!a_string || !b_string) {
			return alert('Both textfields must contain data!')
		}
	 
		var parser = new BelleNuitParser(); 
		
		//------------------------------------------
		//
		// compare
		//
		//------------------------------------------
		
		var self = this;
		var lines = {
			a: parser.parse(a_string),
			b: parser.parse(b_string)
		} 
		console.log('length: '+lines.a.length)
		var differences = []; 
		var longer = lines.a.length > lines.b.length ? 'a' : 'b';
		var shorter = longer == 'a' ? 'b' : 'a';
		var offset = 0; 
		
		$(lines[shorter]).each(function(i) { 
			if ((!lines[shorter][i] || !lines[longer][i+offset]) || lines[shorter][i].text != lines[longer][i+offset].text) {
				offset++;
				var comparison = self.compareLines(lines[shorter][i], lines[longer][i+offset]);
				comparison.line = i;
				differences.push( comparison );
			} 
		});  
		
		
		
		
		if (differences.length == 0) {
			alert('Files are identical!')
		}
		else {
			this.report(differences)
		}
	},
	
	compareLines: function(a,b) { 
		var result = {
			match: true,
			differences: []
		};
		if (!a || !b) {
			result.match = false;
			result.differences.push( {type: 'missing', value_a: a, value_b: b} ); 
		}
		if (a && b && a.text != b.text) {
			result.match = false;
			result.differences.push( {type: 'text', value_a: a.text, value_b: b.text} );
		}
		if (a && b && a.time_in != b.time_in) {
			result.match = false;
			result.differences.push( {type: 'time_in', value_a: a.time_in, value_b: b.time_in} );
		}
		if (a && b && a.time_out != b.time_out) {
			result.match = false;
			result.differences.push( {type: 'time_out', value_a: a.time_out, value_b: b.time_out} );
		}
		return result;
	},
	
	back: function() {
		$('.step2').hide();
		$('.step1').show();	
		setTimeout(onresize, 100);
	},
	
	report: function(diffs) {
		var display = function() {
			// create a table for the output
			var table, thead, tbody, tr;
			table = $('<table class="result datatable" style="width:580px">');
			// table header
			thead = $('<thead>').appendTo(table);
			tr = $('<tr>').appendTo(thead);
			$('<th>').attr({'class': 'line'}).text('Line').appendTo(tr);
			$('<th>').attr({'class': 'diffs'}).text('Differences').appendTo(tr);
			// table body
			tbody = $('<tbody>').appendTo(table);
			$(diffs).each(function(i,diff) {
				console.log('diff: '+diff.line)
				tr = $('<tr data-linenum="'+diff.line+'">').appendTo(tbody); 
				$('<td>').attr({'class': 'line'}).text( diff.line ).appendTo(tr);
				var ul = $('<ul>');
				$(diff.differences).each(function(i,d) {
					var descr = $('<div>');
					descr.append( $('<div>').text( d.type) );
					descr.append( $('<div>').text('A: "'+d.value_a+'"') );
					descr.append( $('<div>').text('B: "'+d.value_b+'"') );
					$('<li>').appendTo(ul).append(descr);
				})
				$('<td>').attr({'class': 'diffs'}).appendTo(tr).append(ul);
			});
			
			// generate html string for the fancybox layer
			var html = '<h3>Comparison result: '+diffs.length+' Differences</h3>';
			html += $('<div>').append(table).html();			
			html += '<div class="buttons fancy-close"><a class="button" onclick="$.fancybox.close()"><span>Close</span></a></div>';
			
			// display fancybox layer
	 
			jQuery.fancybox( 
				html,
				{
		        	'autoDimensions'	: false,
					'width'         		: 600,
					'height'        		: 'auto',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'overlayColor': '#000',
					'onComplete': function() { 
						$('#fancybox-content').css('overflow-y', 'auto');
					}
				}
			);
			/*
			var showLine = function(i) {
				$.fancybox.close();
				$('textarea').scrollTop(0);
				$('textarea')[0].scrollByLines(i);
			}
			$('#fancybox-content tr').click(function() {
				showLine($(this).attr('data-linenum'))
			});
			*/
 
		};
		if (jQuery.fancybox) {
			display()
		}
		else {
			loadFancybox( display );
		}
	}

	 
}

